using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Log;
using GrapeCity.Forguncy.Plugin;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace FaissOperation
{
    [Icon("pack://application:,,,/FaissOperation;component/Resources/Icon.png")]
    [Designer("FaissOperation.Designer.FaissOperationServerCommandDesigner, FaissOperation")]
    [Category("嵌入式向量索引")]
    [OrderWeight(900)]
    public class VKB_Load : Command, ICommandExecutableInServerSideAsync
    {
        [FormulaProperty]
        [DisplayName("集合名")]
        public object KBName { get; set; }


        [FormulaProperty]
        [DisplayName("JSON格式字符串")]
        [Description("本方法因性能较差，已经过时，请使用【加载向量集合】代替。")]
        public object KBJSON { get; set; }


        [DisplayName("强制重新加载")]
        [Description("如果不勾选，系统会检查该向量集合是否已经被加载，性能更好；勾选则会强制重新加载。")]
        public bool ForceReload { get; set; } = false;

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var name = (await dataContext.EvaluateFormulaAsync(KBName))?.ToString() ?? "";
            var json = (await dataContext.EvaluateFormulaAsync(KBJSON))?.ToString() ?? "";

            if (!ForceReload && CollectionManager.Instance.CollectionExists(name))
            {
                dataContext.Log.AppendLine($"向量集合：{name} 已经被加载到内存，本次跳过重新加载。");
                return new ExecuteResult();
            }
            else
            {
                if (!string.IsNullOrEmpty(json))
                {
                    var data = JsonSerializer.Deserialize<Dictionary<int, float[]>>(json);

                    if (data != null && data.Count > 0)
                    {
                        // 推断向量的维度
                        var dimension = data.First().Value.Length;

                        if (!CollectionManager.Instance.CollectionExists(name))
                        {
                            // 创建新的集合，指定维度
                            CollectionManager.Instance.AddCollection(name, new CollectionMetaData(CollectionType.Flat, dimension));
                        }
                        else
                        {
                            if (CollectionManager.Instance.GetCollection(name).Count == 0)
                            {
                                // 如果集合已存在且为空，可更新维度。通用用于初始化时的情况
                                CollectionManager.Instance.GetCollection(name).Dimension = dimension;
                            }

                        }

                        // 准备要插入集合的向量数据
                        List<(int id, float[] vector)> values = new List<(int id, float[] vector)>(data.Count);

                        foreach (var kv in data)
                        {
                            values.Add((kv.Key, kv.Value));
                        }

                        // 插入向量数据到集合中
                        CollectionManager.Instance.GetCollection(name).AddVectors(values);

                        // 处理完毕返回
                        return new ExecuteResult();
                    }

                }

                // 用默认的向量维度创建集合
                if (!CollectionManager.Instance.CollectionExists(name))
                {
                    CollectionManager.Instance.AddCollection(name, new CollectionMetaData(CollectionType.Flat));
                }

                return new ExecuteResult();

            }


        }

        public override string ToString()
        {
            return "使用JSON加载向量集合（已过时）";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }

    }
}
